/* 
 * File:   Challenge.cpp
 * Author: Denys Knertser
 * 
 * Created on February 14, 2012, 2:16 PM
 */
using namespace std;

#include "Challenge.h"
#include <fstream>

Challenge::Challenge() {

}

Challenge::Challenge(string strPack) : PacketFormat(strPack) {
    code = 1;
    setIdentifier();
    serverAuthResponse();
    generateChallengeValue();
    data=string(1,value_size)+value+name;
    length=data.length();
}

string Challenge::getChallenge() {
    return value;
}

int Challenge::setIdentifier() {
    fstream idfile ("id", fstream::in | fstream::out);
    if (idfile==NULL) {
        cout << "Could not find last used identifier file: id\n";
        exit(1);
    }
    idfile >> identifier;
    idfile.seekg(fstream::beg);
    idfile << char(++identifier?identifier:1);
    idfile.close();
    return 1;
}

int Challenge::generateChallengeValue() {
    //we assume here by default the value_size to be 16 octets
    value_size=16;
    unsigned char* buf=new unsigned char[16];
    int result=RAND_pseudo_bytes(buf,16);
    value.assign((const char*)buf,16);
    delete(buf);
    return result;
}

int Challenge::serverAuthResponse() {
    FILE *keyfile = fopen("key.pem", "r");
    if (keyfile==NULL) {
        cout << "Could not find RSA private key: key.pem!\n";
        exit(1);
    }
    RSA *key = PEM_read_RSAPrivateKey(keyfile, NULL, NULL, NULL);
    fclose(keyfile);
    unsigned char* buf=new unsigned char[16];
    int result=RSA_private_decrypt(data.length(),(unsigned char*) data.c_str(), buf, key, RSA_PKCS1_PADDING);
    if (result>0) 
        name.assign((const char*)buf,result);
    else
        name.assign("");
    return result;
}
